<?php


namespace app\api\controller\order;

use app\api\controller\Api;
use app\common\audit\logic\AuditResultLogic;
use app\common\order\model\OrderSettle;
use app\common\order\validate\OrderSettleValidate;
use app\common\order\validate\OrderValidate;
use app\common\system\model\OperateLog;
use think\db\exception\DbException;
use think\Exception;

class Rebate extends Api
{
    public function create()
    {
        $post = $this->request->post();
        $user = $this->request->user;
        if (!isset($post['order']) || !isset($post['settle'])) {
            return error([], "参数错误");
        }

        $order = $post['order'];
        $orderValidate = new OrderValidate();
        if (!$orderValidate->scene('rebate')->check($order)) {
            return  error([], $orderValidate->getError());
        }

        $settle = $post['settle'];
        $settle['company_id'] = $order['company_id'];
        $settle['category_id'] = $order['category_id'];
        $settleValidate = new OrderSettleValidate();
        if (!$settleValidate->check($settle)) {
            return  error([], $settleValidate->getError());
        }

        $source = [];
        $order['order_no'] = date('YmdHis') . uniqid();
        $order['user_id'] = $user['id'];
        $model = new \app\common\order\model\Order();
        $model->startTrans();
        try {
            $model->save($order);
            $orderId = $model->id;

            $modelName = \app\common\order\model\Order::class;
            $source[$modelName] = $orderId;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $settle['order_id'] = $orderId;
        $settle['user_id'] = $user['id'];
        $settleModel = new OrderSettle();
        try {
            $settleModel->save($settle);
            $modelName = \app\common\order\model\OrderSettle::class;
            $source[$modelName] = $settleModel->id;

        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $auditRsLogic = new AuditResultLogic();
        $master = $model->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'rebate'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className=>$row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '创建返佣单成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function save()
    {
        $post = $this->request->post();
        $user = $this->request->user;
        if (!isset($post['order']) || !isset($post['settle'])) {
            return error([], "参数错误");
        }

        $order = $post['order'];
        $orderValidate = new OrderValidate();
        if (!$orderValidate->scene('rebate')->check($order)) {
            return  error([], $orderValidate->getError());
        }

        $settle = $post['settle'];
        $settle['company_id'] = $order['company_id'];
        $settle['category_id'] = $order['category_id'];
        $settleValidate = new OrderSettleValidate();
        if (!$settleValidate->check($settle)) {
            return  error([], $settleValidate->getError());
        }

        $source = [];
        $order['user_id'] = $user['id'];
        $model = new \app\common\order\model\Order();
        $model->startTrans();
        try {
            $orderRow = $model->where('id', $order['id'])->find();
            $orderRow->save($order);
            $orderId = $order['id'];

            $modelName = \app\common\order\model\Order::class;
            $source[$modelName] = $orderId;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $settle['order_id'] = $orderId;
        $settle['user_id'] = $user['id'];
        $settleModel = new OrderSettle();
        try {
            $settleRow = $settleModel->where('id', $settle['id'])->find();
            $settleRow->save($settle);
            $modelName = \app\common\order\model\OrderSettle::class;
            $source[$modelName] = $settle['id'];

        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $auditRsLogic = new AuditResultLogic();
        $master = $orderRow->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'rebate'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className=>$row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '创建返佣单成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function update()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $orderValidate = new OrderValidate();
        if (!$orderValidate->scene('rebate')->check($post)) {
            return error([], $orderValidate->getError());
        }

        $model = new \app\common\order\model\Order();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '数据已不存在');

        $model->startTrans();
        try {
            $post['user_id'] = $user['id'];
            $origin = $row->getData();
            $row->save($post);

            $changed = $row->getData();
            $modelName = \app\common\order\model\Order::class;
            OperateLog::write($user['id'], $post['id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '更新成功');
    }
}